require("prefabutil")

local assets =
{
    Asset("ANIM", "anim/bboy_forsaken_grave.zip"),
}

local prefabs =
{
    "collapse_small",
    "bboy_ghostfire", -- 产出的鬼火（建议在该预制体里加上 tag: bboy_ghostfire）
}

local function onworkfinished(inst)
    inst.components.lootdropper:DropLoot()
    local fx = SpawnPrefab("collapse_small")
    fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
    inst:Remove()
end

-- 夜间产鬼火：黄昏/夜间每 30s 试图产 1 个；2 格内已有鬼火则不产
local GHOST_TAGS = { "bboy_ghostfire" } -- 建议在 bboy_ghostfire 预制体里加：inst:AddTag("bboy_ghostfire")
local GHOST_CHECK_RADIUS = 8            -- “2格地皮内”
local GHOST_SPAWN_PERIOD = 30           -- 30 秒一次

local function CanSpawnGhostfire(inst)
    -- 只在黄昏或夜里
    if not (TheWorld.state.isdusk or TheWorld.state.isnight) then
        return false
    end
    -- 周围有鬼火则不生成
    local x, y, z = inst.Transform:GetWorldPosition()
    local ghosts = TheSim:FindEntities(x, y, z, GHOST_CHECK_RADIUS, GHOST_TAGS)
    return ghosts == nil or #ghosts == 0
end

local function TrySpawnGhostfire(inst)
    if not CanSpawnGhostfire(inst) then
        return
    end

    local x, y, z = inst.Transform:GetWorldPosition()
    -- 让鬼火出现在坟周围 2~4 范围的可走位置
    local offset = FindWalkableOffset(Vector3(x, y, z), math.random() * TWOPI, 2 + math.random() * 2, 12, true, false)

    local sx, sz = x, z
    if offset ~= nil then
        sx = x + offset.x
        sz = z + offset.z
    end

    local ghost = SpawnPrefab("bboy_ghostfire")
    if ghost ~= nil then
        ghost.Transform:SetPosition(sx, 0, sz)

        -- 若你的鬼火里没加标识，这里补一手，方便上面的范围检测
        if not ghost:HasTag("bboy_ghostfire") then
            ghost:AddTag("bboy_ghostfire")
        end

        -- 可选：给它一点初速度做“游荡”，如果鬼火自身有 locomotor/brain 可删掉
        if ghost.Physics ~= nil then
            local ang = math.random() * TWOPI
            local v = 0.5 + math.random() * 0.5
            ghost.Physics:SetVel(math.cos(ang) * v, 0, math.sin(ang) * v)
        end
    end
end

local function StartGhostSpawner(inst)
    if inst._ghosttask == nil then
        inst._ghosttask = inst:DoPeriodicTask(GHOST_SPAWN_PERIOD, TrySpawnGhostfire)
        -- 启动时先试一次
        TrySpawnGhostfire(inst)
    end
end

local function StopGhostSpawner(inst)
    if inst._ghosttask ~= nil then
        inst._ghosttask:Cancel()
        inst._ghosttask = nil
    end
end

local function RefreshGhostSpawner(inst)
    if TheWorld.state.isday then
        StopGhostSpawner(inst)
    else
        StartGhostSpawner(inst)
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()

    inst:SetDeploySmartRadius(0.5)
    MakeObstaclePhysics(inst, .4)

    inst.MiniMapEntity:SetIcon("bboy_forsaken_grave.png")

    inst.AnimState:SetBank("bboy_forsaken_grave")
    inst.AnimState:SetBuild("bboy_forsaken_grave")
    inst.AnimState:PlayAnimation("idle")

    inst:AddTag("structure")

    -- MakeSnowCoveredPristine(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    MakeHauntableWork(inst)
    -- MakeSnowCovered(inst)

    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(4)
    inst.components.workable:SetOnFinishCallback(onworkfinished)

    inst:AddComponent("inspectable")

    inst:AddComponent("lootdropper")

    --------------------------------------------------------------------------
    inst:WatchWorldState("isday", RefreshGhostSpawner)
    inst:WatchWorldState("isdusk", RefreshGhostSpawner)
    inst:WatchWorldState("isnight", RefreshGhostSpawner)
    inst:DoTaskInTime(0, RefreshGhostSpawner)
    inst:ListenForEvent("onremove", function() StopGhostSpawner(inst) end)
    --------------------------------------------------------------------------

    return inst
end

return Prefab("bboy_forsaken_grave", fn, assets, prefabs),
    MakePlacer("bboy_forsaken_grave_placer", "bboy_forsaken_grave", "bboy_forsaken_grave", "idle")
